<template>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column
      label="预约时间"
      prop="updatetime"
      :formatter="appointment"
    >
    </el-table-column>
    <el-table-column label="姓名" prop="patientname" />
    <el-table-column label="身份证" prop="patientid" :formatter="hideidNumber">
    </el-table-column>

    <el-table-column label="预约部门" prop="department" />
    
    <el-table-column label="预约医生" prop="doctorname" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <!-- <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          修改预约
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          取消预约
        </el-button>
      </template> -->
    </el-table-column>
  </el-table>
  <!-- 编辑对话框 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="修改预约"
    width="500"
    align-center
  >
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="姓名">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="身份证">
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item label="预约日期">
        <el-input v-model="form.appointmentTime" />
      </el-form-item>
      <el-form-item label="部门">
        <el-input v-model="form.department" />
      </el-form-item>
      <el-form-item label="选择医生">
        <el-input v-model="form.selectedDoctor" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认修改</el-button>
        <el-button @click="Cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "../request/index";
import { onMounted } from "vue";

const centerDialogVisible = ref(false);
interface appointmentDoctors {
  appointmentTime: string;
  name: string;
  id: string;
  department: string;
  selectedDoctor: string;
}

const search = ref("");
const filterTableData = computed(() => {
  if (!tableData.value) {
    return [];
  }
  return tableData.value.filter(
    (data) =>
      !search.value ||
      data.patientname.toLowerCase().includes(search.value.toLowerCase())
  );
});
// 预约日期
const appointment = (row: any, column: any, cellValue: string) => {
  const regex =
    /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).\d{3}\+\d{2}:\d{2}/;
  const match = cellValue.match(regex);
  const formattedTime = `${match[1]}-${match[2]}-${match[3]} ${match[4]}:${match[5]}:${match[6]}`;
  return formattedTime
};

// 隐藏身份证
const hideidNumber = (row: any, column: any, cellValue: string) => {
  return cellValue.replace(/(\d{5})\d{4}(\d{4})/, "$1****$2");
};

onMounted(() => {
  getAppointments();
});

// 获取后端预约数据
const getAppointments = async () => {
  console.log("获取数据");
  try {
    const response = await service.get("/Diagnosis/getAllreserve");
    tableData.value = response.data;
    console.log(tableData.value);
  } catch (error) {
    console.error("获取预约信息失败：", error);
  }
};

// 编辑
const form = reactive({
  appointmentTime: "",
  name: "",
  id: "",
  department: "",
  selectedDoctor: "",
});
// 备份
const originalData = reactive({
  appointmentTime: "",
  name: "",
  id: "",
  department: "",
  selectedDoctor: "",
});
let EditIndex = 0;

// 编辑
const handleEdit = (index: number, row: appointmentDoctors) => {
  EditIndex = index;
  originalData.appointmentTime = row.appointmentTime;
  originalData.name = row.name;
  originalData.id = row.id;
  originalData.department = row.department;
  originalData.selectedDoctor = row.selectedDoctor;

  form.appointmentTime = row.appointmentTime;
  form.name = row.name;
  form.id = row.id;
  form.department = row.department;
  form.selectedDoctor = row.selectedDoctor;

  centerDialogVisible.value = true;
};
// 确认修改
const onSubmit = () => {
  if (EditIndex >= 0) {
    tableData.value[EditIndex] = {
      appointmentTime: form.appointmentTime,
      name: form.name,
      id: form.id,
      partment: form.department,
      selectedDoctor: form.selectedDoctor,
    };
    centerDialogVisible.value = false;
  } else {
    ElMessage.error("请先选择要修改的预约");
  }
};

// 取消
const Cancle = () => {
  centerDialogVisible.value = false;
  tableData.value[EditIndex] = originalData;
};

// 删除
const handleDelete = async (index: number, row: appointmentDoctors) => {
  console.log(index, row);
  ElMessageBox.confirm("确认取消预约?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "取消成功",
      });
      console.log(index, row);
      // 删除数据
      tableData.value.splice(index, 1);
      // 后端删除预约信息
      //   try {
      //   const response = await service.delete(`/api/appointments/${row.id}`);
      //   if (response.status === 200) {
      //     ElMessage({
      //       type: "success",
      //       message: "删除成功",
      //     });
      //     tableData.value.splice(index, 1);
      //   } else {
      //     ElMessage({
      //       type: "error",
      //       message: "删除失败",
      //     });
      //   }
      // } catch (error) {
      //   console.error('删除预约失败：', error);
      // }
      console.log(tableData);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消失败",
      });
    });
};

// table 数据  开始请求数据
const tableData = ref([

]);
</script>
